package cn.cubic.sys.modular.customerinfo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.cubic.core.exception.ServiceException;
import cn.cubic.core.factory.PageFactory;
import cn.cubic.core.pojo.page.PageResult;
import cn.cubic.sys.modular.customerinfo.entity.CustomerInfo;
import cn.cubic.sys.modular.customerinfo.mapper.CustomerInfoMapper;
import cn.cubic.sys.modular.customerinfo.model.param.CustomerInfoParam;
import cn.cubic.sys.modular.customerinfo.service.CustomerInfoService;
import cn.cubic.sys.modular.customerinfo.enums.CustomerInfoExceptionEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 客户信息表 服务实现类
 */
@Service
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Override
    public PageResult<CustomerInfo> page(CustomerInfoParam customerInfoParam) {

        // 构造条件
        LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();

        // 查询分页结果
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<CustomerInfo> list(CustomerInfoParam customerInfoParam) {

        // 构造条件
        LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();

        return this.list(queryWrapper);
    }

    @Override
    public void add(CustomerInfoParam customerInfoParam) {

        // 将dto转为实体
        CustomerInfo customerInfo = new CustomerInfo();
        BeanUtil.copyProperties(customerInfoParam, customerInfo);

        this.save(customerInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(CustomerInfoParam customerInfoParam) {
        this.removeById(customerInfoParam.getId());
    }

    @Override
    public void edit(CustomerInfoParam customerInfoParam) {

        // 根据id查询实体
        CustomerInfo customerInfo = this.queryCustomerInfo(customerInfoParam);

        // 请求参数转化为实体
        BeanUtil.copyProperties(customerInfoParam, customerInfo);

        this.updateById(customerInfo);
    }

    @Override
    public CustomerInfo detail(CustomerInfoParam customerInfoParam) {
        return this.queryCustomerInfo(customerInfoParam);
    }



    /**
     * 获取客户信息表
     */
    private CustomerInfo queryCustomerInfo(CustomerInfoParam customerInfoParam) {
        CustomerInfo customerInfo = this.getById(customerInfoParam.getId());
        if (ObjectUtil.isEmpty(customerInfo)) {
            throw new ServiceException(CustomerInfoExceptionEnum.NOT_EXISTED);
        }
        return customerInfo;
    }
}